package com.sebscape.sebcms.security.services;

import javax.servlet.http.HttpServletRequest;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.StrutsStatics;

import com.sebscape.sebcms.Constants;

public class CmsLoginInterceptor extends AbstractInterceptor implements StrutsStatics {

	private static final long serialVersionUID = -6669254945284973914L;
	private static Log log = LogFactory.getLog( CmsLoginInterceptor.class );
	
	public static final String SUCCESS = "success";
	public static final String DENIED = "denied";
	private String uri; // the uri which will be uses by action-result for success.
	
	public String getUri(){
		return this.uri;
	}
	
	public String intercept (ActionInvocation invocation) throws Exception {
		log.debug( "CmsLoginInterceptor invoked...");
	    // Get the action context from the invocation so we can access the
	    // HttpServletRequest and HttpSession objects.
	    final ActionContext context = invocation.getInvocationContext ();
	    HttpServletRequest request = (HttpServletRequest) context.get(HTTP_REQUEST);
		try {
			// do the processing.
			processBefore( request );
			return invocation.invoke ();
		} catch (Exception e) {
			// THis means the user is NOT logged in.
			log.debug("Exception raised in SimpleFilter: " + e.getMessage() );
			return DENIED;
		}// end catch
	} // end method

	private void processBefore(HttpServletRequest request)
	throws Exception{
		// check for the User in the session.
		if( request.getSession().getAttribute( Constants.ATTRIB_CURRENT_USER ) != null ){
			log.debug( "Found sebcms_current_user in session, so continue...");
			// the user is logged in so we can allow the chain to continue.
			return;
		} else {
			log.debug( "NOT Found ATTRIB_CURRENT_USER in session, so stop.");
			log.debug( "NOT Found ATTRIB_CURRENT_USER in session, so stop.");
			// the user is not logged in so lets redirect them to the login page.
			log.debug("storing in session.j_uri: " + request.getRequestURL().toString() );
			request.getSession().setAttribute( "j_uri", request.getRequestURL().toString() );
			throw new Exception( "notLoggedIn" );
		}
	}
	
}